/*
 * Created by SharpDevelop.
 * User: tentus
 * Date: 2006-10-21
 * Time: 18:56
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;

namespace ActionManager
{
	/// <summary>
	/// Description of ScheduleServer.
	/// </summary>
	public partial class ScheduleServer
	{
		string xml;
		List<SSchedule> schedule_list;
		ActionManagerXml xmlManager;
		
		public ScheduleServer()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();	
			
			xml = "";
			xmlManager    = new ActionManagerXml();
			schedule_list = new List<SSchedule>();
		}
		
		public void Notify(string _xml)
		{
			if (xml==_xml)return;
			
			xml = _xml;
			timer1.Enabled = false;
			
			schedule_list.Clear();
			xmlManager.GetScheduleList(xml, schedule_list);
			
			timer1.Enabled = true;
		}
		
		private bool IsEqualTime(DateTime _now, DateTime _date, string _frequency)
		{						
			if (_now<_date || _now.Hour!=_date.Hour || _now.Minute!=_date.Minute)return false;						
			
			if (_now==_date)return true;	//Once																	
			
			if (_frequency=="Daily")return true;
			
			if (_frequency=="Weekly" && _now.DayOfWeek==_date.DayOfWeek)return true;
			
			if (_frequency=="Workdays" && (int)(_now.DayOfWeek)>0 && (int)(_now.DayOfWeek)<6)return true;
			
			if (_frequency=="Monthly" && _now.Day==_date.Day)return true;
			
			if (_frequency=="Yearly" && _now.Day==_date.Day && _now.Month==_date.Month)return true;
			
			return false;
		}
		
		void Timer1Tick(object sender, System.EventArgs e)
		{
			DateTime date_now = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, 0);
			
			for (int i=0; i<schedule_list.Count; ++i)
			{
				if (IsEqualTime(date_now, schedule_list[i].date, schedule_list[i].frequency))
					xmlManager.ExecuteGroup(xml, schedule_list[i].nr_grupy);
			}
		}			
	}
}
